//
// Created by user on 2022/3/15.
//

#include <iostream>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
    };

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode* dummy = new ListNode();
    ListNode* curr = dummy;
    int carry = 0;
    while (l1 || l2) {
        int x = l1 ? l1->val : 0;
        int y = l2 ? l2->val : 0;

        int sum = x + y + carry;
        curr->next = new ListNode(sum % 10);
        curr = curr->next;
        carry = sum / 10;

        if (l1) l1 = l1->next;
        if (l2) l2 = l2->next;
    }
    if (carry != 0) curr->next = new ListNode(carry);
    return dummy->next;
}